<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chat</title>
</head>
<body>
<div id="login-div">
    <input id="input" type="text"/><br/>
    <input id="buttonLogin" type="button" value="登录" onclick="login()"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input id="buttonLogout" type="button" value="退出"/><br/><br/>

    <input id="inputSay" type="text"/><br/>
    <input id="buttonSay" type="button" value="发言"/><br/>
</div>

<div id="container">

</div>

<script>
    var url = "ws://localhost:8081/chat2";
    var ws;

    var sleep = function(time) {
        var startTime = new Date().getTime() + parseInt(time, 10);
        while(new Date().getTime() < startTime) {}
    };

    function login() {
        var uid = document.getElementById("input").value;

        ws = new WebSocket(url);

        //进入直播间，退出直播间消息
        var messageEnterIn = {
            type: 1,
            uid: uid
        };
        var messageEnterOut = {
            type: 2,
            uid: uid
        };

        ws.onopen = function (ev) {
            ws.send(JSON.stringify(messageEnterIn));
            console.log("open");
        };

        /**
         * 经测试，浏览器端刷新页面，或关闭页面时，onclose和onerror没机会执行（因为页面关闭或刷新,websocket对象已销毁）
         * websocket服务端下线时，才会执行
         * @param ev
         */
        ws.onclose = function (ev) {
            ws.send(JSON.stringify(messageEnterOut));
            console.log("close");
        };

        ws.onerror = function (ev) {
            ws.send(JSON.stringify(messageEnterOut));
            console.log("error");

            ws.close(3001, "error");
        };

        ws.onmessage = function (ev) {
            var p = document.createElement("p");
            p.innerText = ev.data;
            document.getElementById("container").appendChild(p);
        };

        var logout = document.getElementById("buttonLogout");
        logout.onclick = function () {
            ws.send(JSON.stringify(messageEnterOut));
            ws.close(3002, "exit");
        };

        var say = document.getElementById("buttonSay");
        say.onclick = function () {
            var inputSay = document.getElementById("inputSay").value;

            //发言消息
            var message = {
                type: 3,
                uid: uid,
                text: inputSay
            };
            ws.send(JSON.stringify(message));
        };
    }

</script>
</body>
</html>